import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class clean
{
    public static void rmOld(String dir)
    {
        try
        {
            File root = new File(dir);
            if (!root.exists() || !root.isDirectory())
                throw new Exception(dir + " is not Directory");
            List<String> childs = new ArrayList<String>();
            for (String child : root.list())
            {
                childs.add(child);
            }
            Collections.sort(childs);
            String preName = "";
            File preFile = null;
            String name = "";
            Pattern p = Pattern.compile("([\\w\\._]*)_\\d.*");
            Matcher m;
            for (int i = 0; i < childs.size(); i++)
            {
                m = p.matcher(childs.get(i));
                if (m.find())
                {
                    name = m.group(1);
                    if (name.equals(preName))
                    {
                        String fileName = preFile.getName();
                        if (!fileName.contains("tigris"))
                        {
                            System.out.println("delete:" + dir + "/" + fileName);
                            rm(new File(dir + "/" + fileName));
                        }
                    }
                    preFile = new File(childs.get(i));
                    preName = name;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void rm(File dir)
    {
        if (dir.isDirectory())
            for (File file : dir.listFiles())
            {
                if (file.isFile())
                    file.delete();
                else if (file.isDirectory())
                    rm(file);
            }
        dir.delete();
    }

    public static void main(String[] args)
    {
        rmOld("/home/yys/Programs/eclipse/plugins");
        rmOld("/home/yys/Programs/eclipse/features");
    }
}
